var express = require('express')
var router = express.Router()
var { FindOneDataMore, InsertManyData, UpdateTableData, FindTableData, RemoveTableData } = require('../db')
const { user_model, anno_model,party_model } = require('../db/model')
var axios = require("axios")
const { getToken, checkToken } = require('../utils/token')
var multer = require("multer")   //上传文件

//   react  接口的接口


//注册
router.post("/register", (req, res) => {
    var body = req.body;
    FindOneDataMore({
        model: user_model,
        query: {
            $or: [
                {
                    username: body.username
                },
                {
                    phone: body.phone
                }
            ]
        },
        res,
        callback(result) {
            if (result) {
                res.json({
                    code: 401,
                    msg: "用户已经创建，重新注册",
                    result
                })
            } else {
                body.time = new Date()
                InsertManyData({
                    model: user_model,
                    data: body,
                    msg: "注册成功",
                    res
                })
            }
        }
    })
})

//登录
router.post("/login", (req, res) => {
    var body = req.body;
    FindOneDataMore({
        model: user_model,
        query: body,
        res,
        callback(result) {
            if (result) {
                // Token  
                var token = getToken(body)  // 用户名和密码得到一个 token 
                res.json({
                    code: 200,
                    msg: "登录成功",
                    result,
                    token 
                })
            } else {
                res.json({
                    code: 401,
                    msg: "登录失败,用户名或者密码错误",
                    result,
                })
            }
        }
    })
})

//获取个人信息
router.post("/getusreinfo",(req,res)=>{
    checkToken(req,res,({phone})=>{
        FindOneDataMore({
            model:user_model,
            query:{phone},
            msg:'获取个人信息成功',
            res 
        })
    })
})
//主页修该密码
router.post("/changePass",(req,res)=>{
    var body = req.body
    checkToken(req,res,({phone})=>{
        FindOneDataMore({
            model:user_model,
            query:{phone,password:body.oldpass},
            res,
            callback:result=>{
                if(result){
                    UpdateTableData({
                        model:user_model,
                        query:{phone},
                        data:{
                            $set:{
                                password:body.newpass
                            }
                        },
                        res,
                        msg:"密码修改成功"
                    })
                }else{
                    res.json({
                        code:401,
                        msg:"输入的旧密码错误",
                        result:null
                    })
                }
            }
        })
    })
})

//修改密码
router.post("/changeCode",(req,res)=>{
    var body = req.body
    var phone = req.body.phone
    UpdateTableData({
        model: user_model,
        query: { phone },
        data: {
            $set: body
        },
        res,
    })
})

// 发送验证码 
router.post("/sendcaptcha",(req,res)=>{
    var body = req.body;
    // 先去查询一下 
    // 再去发送验证码 
    console.log(body);
    FindOneDataMore({
        model:user_model,
        query:body,
        res,
        callback(result){
            if(result){
                // 发送验证code 
                axios.get("http://47.104.209.44:3333/captcha/sent",{
                    params:body // {phone:xxxxxx}
                })
                .then(({data})=>{
                    console.log(data)
                    if(data.code==200){
                        res.json({
                            code:200,
                            data,
                            msg:'验证码发送成功'
                        })
                    }else{
                        res.json({
                            code:401,
                            data,
                            msg:'验证码发送失败'
                        })
                    }
                    
                })
            }else{
                res.json({
                    code:401,
                    msg:'手机号未注册,请先注册',
                    result 
                })
            }
        }
    })
})

// 校验验证码 
router.post("/chechcaptcha",(req,res)=>{
    var body = req.body;  // phone captcha
    FindOneDataMore({
        model:user_model,
        query:{ phone: body.phone },
        res,
        callback(result){
            if(result){
                // 发送验证code 
                axios.get("http://47.104.209.44:3333/captcha/verify",{
                    params:body // {phone:xxxxxx}
                })
                .then(({data})=>{
                    // console.log(data);
                    // data.code==200
                    if(data.code==200){
                        var token = getToken({
                            username:result.username,
                            password:result.password,
                            phone:result.phone 
                        })
                        res.json({
                            code:200,
                            data,
                            msg:'验证码校验成功',
                            token
                        })
                    }else{
                        res.json({
                            code:401,
                            data,
                            msg:'验证码校验失败'
                        })
                    }
                })
            }else{
                res.json({
                    code:401,
                    msg:'手机号未注册,请先注册',
                    result 
                })
            }
        }
    })
})

//上传文件
const storage = multer.diskStorage({  // 硬盘存储 
    destination: function (req, file, cb) {
      cb(null, './public/images/uploads')
    },
    filename: function (req, file, cb) {
      const uniqueSuffix = "WH2114__"+Date.now() + '-' + Math.round(Math.random() * 1E9)   // 文件名、
      cb(null, file.fieldname + '-' + uniqueSuffix + file.originalname)
    }
})
  
// 上传文件 
const upload = multer({ storage: storage }).any()

router.post("/uploadFile",upload,(req,res)=>{
    var path = req.files[0].path
    res.json({
        code:200,
        msg:"上传成功",
        path,
        result:path 
    })
})


//修改用户信息
router.post("/changeUserInfo",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({phone})=>{
        UpdateTableData({
            model:user_model,
            query:{phone},
            data:{
                $set:body
            },
            res,
            msg:"成功"
        })
    })
})
// ------------------权限-------------
//获取用户列表
router.post('/roleList',(req,res)=>{
    checkToken (req,res,({phone})=>{
        FindTableData({
            model :user_model,
            query:{},
            msg:"成功",
            res
        })
    })
})
//删除用户
router.post("/roleDelete",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({phone})=>{
        RemoveTableData({
            model:user_model,
            query:{
                _id:body._id
            },
            msg:'删除成功',
            res
        })
    })
})
//修改用户
router.post("/roleUpdate",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({phone})=>{
        UpdateTableData({
            model:user_model,
            query:{
                _id:body._id
            },
            data:body,
            msg:"修改成功",
            res
        })
    })
})
//查询一公告
router.post('/roleOne',(req,res)=>{
    var body = req.body
    checkToken(req,res,({phone})=>{
        FindOneDataMore({
            model:user_model,
            query:{
                _id:body._id
            },
            msg:"查询成功",
            res
        })
    })
})


// ------------公告----------
//公告列表
router.post('/annoList',(req,res)=>{
    var query = {}
    var {keyword,type} = req.body
    if(keyword && type){
        query = {
            title :new RegExp(keyword),
            type:type*1
        }
    }else if(keyword){
        query={
            $or:[
                {
                    title:new RegExp(keyword)
                },
                {
                    content:new RegExp(keyword)
                }
            ]
        }
    }else if(type){
        query = {
            type :type * 1
        }
    }
    checkToken (req,res,({phone})=>{
        FindTableData({
            model :anno_model,
            query:query,
            msg:"成功",
            res
        })
    })
})
//公告添加
router.post("/annoAdd",(req,res)=>{
    var body =req.body
    body.time = new Date()
    checkToken(req,res,({phone})=>{
        InsertManyData({
            model:anno_model,
            data:body,
            res,
            msg:"公告添加成功"
        })
    })
})

//查询一公告
router.post('/annoOne',(req,res)=>{
    var body = req.body
    checkToken(req,res,({phone})=>{
        FindOneDataMore({
            model:anno_model,
            query:{
                _id:body._id
            },
            msg:"查询成功",
            res
        })
    })
})
//删除公告
router.post("/annoDelete",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({phone})=>{
        RemoveTableData({
            model:anno_model,
            query:{
                _id:body._id
            },
            msg:'删除成功',
            res
        })
    })
})
//修改公告
router.post("/annoUpdate",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({phone})=>{
        UpdateTableData({
            model:anno_model,
            query:{
                _id:body._id
            },
            data:body,
            msg:"修改成功",
            res
        })
    })
})

module.exports = router;